package com.fang.system.rpc.callback;

import com.fang.system.rpc.model.PackageMsg;

import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author fanglingxiao
 * @version 1.0
 * @description TODO
 * @date 2022/7/16 10:54 下午
 **/
public class ResponseMappingCallback {
    private static ConcurrentHashMap<String, CompletableFuture> mapping = new ConcurrentHashMap<>();


    public static void runCallback(PackageMsg resPackageMsg) {
        if (Objects.isNull(resPackageMsg) || Objects.isNull(resPackageMsg.getHeader())) {
            return;
        }
        CompletableFuture cb = mapping.get(resPackageMsg.getHeader().getRequestId());
        cb.complete(resPackageMsg.getContent().getRes());
        removeCallback(resPackageMsg.getHeader().getRequestId());
    }

    private static void removeCallback(String requestId) {
        mapping.remove(requestId);
    }

    public static void addCallback(String requestId, CompletableFuture<String> res) {
        mapping.putIfAbsent(requestId, res);
    }
}
